package ezonsport.android.common.eventManger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;



public class MyEventManager {

	 private class Listener {
		
		private final static String TAG="Listener";
		
		private Observer observer;
		private MyEventManager.MyReceiver myReceiver;
		private IntentFilter intentFilter;
		
		public Listener(Observer observer)
		{
			this.observer=observer;
			this.myReceiver=new MyEventManager().new MyReceiver();
			this.intentFilter=new IntentFilter();
		}

		public Listener(Observer observer,String  action)
		{
			this.observer=observer;
			this.myReceiver=new MyEventManager().new MyReceiver();
			this.intentFilter=new IntentFilter(action);
		}
		
		
		public Observer getObserver() {
			return observer;
		}
		public void setObserver(Observer observer) {
			this.observer = observer;
		}
		public MyEventManager.MyReceiver getMyReceiver() {
			return myReceiver;
		}
		public void setMyReceiver(MyEventManager.MyReceiver myReceiver) {
			this.myReceiver = myReceiver;
		}
		public IntentFilter getIntentFilter() {
			return intentFilter;
		}
		public void setIntentFilter(IntentFilter intentFilter) {
			this.intentFilter = intentFilter;
		}
		
		public boolean isEqualObserver(Observer observer)
		{
			boolean result=false;
			if(this.observer.equals(observer))
			{
				result=true;
			}
			else
			{
				result=false;
			}
			return result;
		}
		
		public void  registerBroadCast(Context context)
		{
			context.registerReceiver(myReceiver, intentFilter);
			Log.i(TAG, "向系统注册广播"); 
		}
		
		public void  unRregisterBroadCast(Context context)
		{
			context.unregisterReceiver(myReceiver);
			Log.i(TAG, "向系统注销广播");
		}
		
		public void deleteAction(String action)
		{
			IntentFilter newIntentFilter=new IntentFilter();
			for(int i=0;i<intentFilter.countActions();i++)
			{
				if(!intentFilter.getAction(i).equals(action))
				{
					newIntentFilter.addAction(intentFilter.getAction(i));
				}
			}
			intentFilter=newIntentFilter;
		}
		
		
		

		
		public boolean isActionExist(String action)
		{
			return intentFilter.hasAction(action);
			
		}
		
		public boolean addAction(String action)
		{
			boolean result=false;
			if(intentFilter.hasAction(action))
			{
				intentFilter.addAction(action);
				result=true;
			}
			else
			{
				result=false;
			}
			return result;
			
		}

		
	}
	
	private static HashMap<String,List<Listener>> listenermap=new HashMap<String,List<Listener>>();
	
	
	private final static String TAG="MyEventManager";
	
	
	/**
	 * 注册普通监听者
	 * @param eventName
	 * @param observer
	 * @return
	 */
	public static  boolean  Register(Observer observer,String eventName)
	{
		boolean result=false;
		Log.d(TAG, "注册开始");
		if(listenermap.containsKey(eventName))
		{
			Log.d(TAG, "已存在的事件"+eventName);
			List<Listener> listeners=listenermap.get(eventName);
			
			if(getListenerInListenersByObserver(listeners,observer)==null)
			{
				Listener listener=new MyEventManager().new Listener(observer);
				listeners.add(listener);
				Log.d(TAG, "添加监听者成功");
				result=true;
			}
			else
			{
				result=false;
				Log.d(TAG, "事件"+eventName+" 监听失败，事件中已存监听者");
			}
			
		}
		else
		{
			Log.d(TAG, "创建新的事件"+eventName);
			List<Listener> listeners=new ArrayList<Listener>();
			Listener listener=new MyEventManager().new Listener(observer);
			listeners.add(listener);
			listenermap.put(eventName, listeners);
			Log.d(TAG, "添加事件"+eventName+"成功");
		    result=true;
		}
		return result;
	}
	
	
	/**
	 * 注册广播监听者
	 * @param receiver
	 * @param eventName
	 * @param filter
	 */
	public  static boolean RegisterBroadCastLisener(Context context,Observer observer, String eventName)
	{
		boolean result=true;
		
		Log.d(TAG, "广播"+eventName+"注册开始");

		if(listenermap.containsKey(eventName))
		{
			Log.d(TAG, "已存在的事件"+eventName);
			List<Listener> listeners=listenermap.get(eventName);
			
			Listener getlistener=getListenerInListenersByObserver(listeners,observer);
			if(getlistener==null)
			{
				getlistener=new MyEventManager().new Listener(observer,eventName);
				getlistener.registerBroadCast(context);
				listeners.add(getlistener);
				Log.i(TAG, "成功,监听者监听事件和广播");
				result=true;
			}
			else
			{			
				Log.d(TAG, "事件"+eventName+" 监听失败，事件中已存监听者");
				if(getlistener.getIntentFilter().countActions()!=0)
				{
					if(!getlistener.isActionExist(eventName))
					{
	
						Log.i(TAG, "成功，添加广播"+eventName);
						reRigsterBroadCast(context,getlistener,eventName);
						result=true;
	
					}
					else
					{
						Log.i(TAG, "监听者已监听广播 "+eventName);
						result=false;
					}	
				}
				else
				{
					Log.d(TAG, "监听者未监听广播 "+eventName);
					getlistener.addAction(eventName);
					getlistener.registerBroadCast(context);
					Log.d(TAG, "成功，注册广播 事件"+eventName);
				}
			}		
		}
		else
		{
			Log.d(TAG, "创建新的事件和广播"+eventName);
			List<Listener> listeners=new ArrayList<Listener>();	 
			Listener listener=new MyEventManager().new Listener(observer,eventName);
			listeners.add(listener);
			listenermap.put(eventName, listeners);
			listener.registerBroadCast(context);
			Log.d(TAG, "添加事件和广播"+eventName+"成功");
					
		    result=true;
		}
		
		return result;
	}
	
	
	
	
	
	/**
	 * 删除事件的全部普通监听者
	 * @param eventName
	 * @return
	 */
	public static  boolean unRegisterAllNormalLisenerByEventName(String eventName)
	{
		boolean result=false;
		
		Log.i(TAG, "删除事件的全部普通监听者，删除开始"+listenermap.size());
		result=unRegisterAllLisenerByEventName	(null, eventName,2);
		return result;
	}
	
	/**
	 * 删除事件的全部监听者
	 * @param context
	 * @param eventName
	 * @return
	 */
	public static   boolean unRegisterAllLisenerByEventName(Context context,String eventName)
	{
		boolean result=false;
		Log.i(TAG, "开始，删除事件"+eventName+"的全部监听者");
		
		result=unRegisterAllLisenerByEventName	( context, eventName,0);
		Log.i(TAG, "完成，删除事件"+eventName+"的全部监听者");
		return result;
	}
	
	
	
	
	/**
	 * 删除事件的全部广播监听者，未删除普通监听者
	 * @param context
	 * @param eventName
	 * @return
	 */	
	public static   boolean unRegisterAllBroadCastLisenerByEventName(Context context,String eventName)
	{
		boolean result=false;
		Log.i(TAG, "开始，删除事件"+eventName+"的全部广播监听者");
		
		result=unRegisterAllLisenerByEventName	( context, eventName,1);
		
		Log.i(TAG, "完成，删除事件"+eventName+"的全部广播监听者");
		return result;
	}
	
	/**
	 * 删除监听者的所有普通事件 
	 * @param observer
	 * @return 
	 */
	public static boolean unRegisterAllNormalEvents(Observer observer)
	{
		boolean result=false;
		Log.i(TAG, "开始，注销监听者的全部普通事件");
		result=unRegisterAllEvents( null, observer,2);
		Log.i(TAG, "完成，注销监听者的普通事件");
		return result;
	}
	
	/**
	 * 删除监听者的所有事件
	 * @param context
	 * @param observer
	 * @return
	 */
	public static boolean unRegisterAllEvents(Context context,Observer observer)
	{
		boolean result=false;
		Log.i(TAG, "开始，注销监听者的全部事件");
		result=unRegisterAllEvents( context, observer,0);
		Log.i(TAG, "完成，注销监听者的事件");
		return result;
	}
	
	
	
	
	
	/**
	 * 删除监听者的所有广播事件，即监听者从广播监听者变为普通监听者
	 * @param observer
	 * @return
	 */
	public static boolean unRegisterAllBroadCastEvents(Context context,Observer observer)
	{
		boolean result=false;
		Log.i(TAG, "开始，注销监听者的全部广播事件");
		result=unRegisterAllEvents( context, observer,1);
		Log.i(TAG, "完成，注销监听者的广播事件");
		return result;
	}

	

	/**
	 * 解除广播，不解除监听的事件
	 * @param context
	 * @return
	 */
	public static boolean unRegisterBroadCastLisener(Context context,Observer observer, String eventName)
	{
		boolean result=false;
		
		Log.d(TAG, "注销广播监听者开始");
		if(listenermap.containsKey(eventName))
		{
			List<Listener> listeners=listenermap.get(eventName);
			Listener getlistener=getListenerInListenersByObserver(listeners,observer);	
			if(getlistener!=null)
			{				
				if(getlistener.isActionExist(eventName))
				{
					reRigsterBroadCast(context,getlistener,eventName);

					result=true;
				}
				else
				{
					Log.w(TAG, "广播"+eventName+"不存在");
					result=false;
				}
			}
			else
			{
				Log.d(TAG, "事件"+eventName+"未存在的监听者");
				result=true;
			}

			Log.d(TAG, "事件 "+eventName+" 剩余监听者数: "+listenermap.get(eventName).size());
		}
		else
		{
			Log.w(TAG, "未存在的事件:"+eventName);
			result=false;
		}

		
		return result;
		
	}
	/**
	 * 注销普通监听者
	 * @param observer
	 * @param eventName
	 * @return 事件有广播则返回falses
	 */
	public static boolean unRegisterNormalListener(Observer observer,String eventName)
	{
		boolean result=false;
		result=unRegister(null,observer,eventName,0);
		return result;
	}
	
	/**
	 * 删除事件监听者，并删除事件
	 * @param context
	 * @param observer
	 * @param eventName
	 * @return
	 */
	public static boolean unRegisterListener(Context context,Observer observer,String eventName)
	{
		boolean result=false;
		result=unRegister(context,observer,eventName,1);
		return result;
	}
	
	
	
	public static boolean NotifyEvent(Object notifyObj,String eventName,Intent data )
	{
		boolean result=false;
		if(listenermap.containsKey(eventName))
		{
			List<Listener> listeners=listenermap.get(eventName);
			Log.i(TAG, "开始通知，事件"+eventName+"，监听者数目:"+listeners.size());
			for(Iterator<Listener> ite =listeners.iterator();ite.hasNext();)
			{
				Observer ober=ite.next().getObserver();
				ober.onReceive(notifyObj,eventName,data);
			}
			Log.d(TAG, "通知完毕");
			result=true;
		}
		else
		{
			Log.w(TAG, "未存在的事件:"+eventName);
		}
		Log.i(TAG, "通知结束");
		return result;
	}
	
	public static  boolean IsEventNameExit(String eventName)
	{	
		boolean result=false;
		if(listenermap.containsKey(eventName))
		{
			result=true;
		}
		return result;
	}
	
	
	public static  boolean IsObserverExit(Observer observer,String eventName)
	{	
		boolean result=false;
		if(IsEventNameExit(eventName))
		{
			Listener getlistener=getListenerByObserverAndEventName(observer,eventName);
			if(getlistener!=null)
			{
				result=true;
			}
			else
			{
				result=false;
			}
			
		}
		return result;
	}
	
	
	
	public class MyReceiver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String action =intent.getAction();
			Log.i(TAG, "广播到达:"+action);
			Log.i(TAG, "开始通知");
			Observer observer=MyEventManager.getObserverByMyReceiverAndEventName(this,action);
			observer.onReceive(this,action, intent);
			//NotifyEvent(action,intent);	
		
		}
		
	}


	private static Listener getListenerInListenersByObserver(List<Listener> listeners,Observer observer)
	{
		Listener listener=null;
		for(Iterator<Listener> iter=listeners.iterator();iter.hasNext();)
		{
			Listener tempListener=iter.next();
			if(tempListener.isEqualObserver(observer))
			{
				listener=tempListener;
				break;
			}
		}
		return listener;
	}
	
	private static Listener getListenerByObserverAndEventName(Observer observer,String eventName)
	{
		List<Listener> listeners=listenermap.get(eventName);
		return getListenerInListenersByObserver(listeners,observer);
	}
	
	private static Observer getObserverByMyReceiverAndEventName(MyReceiver myReceiver,String eventName)
	{
		Observer observer=null;
		List<Listener> listeners=listenermap.get(eventName);
		for(Iterator<Listener> iter=listeners.iterator();iter.hasNext();)
		{
			Listener tempListener=iter.next();
			if(tempListener.getMyReceiver().equals(myReceiver))
			{
				Log.d(TAG, "找到观察者");
				observer=tempListener.getObserver();
				break;
			}
		}
		
		return observer;
		
	}
	
	
	private static boolean unRegister(Context context,Observer observer,String eventName,int flag)
	{
		//flag==0 注销普通监听者  事件有广播则返回falses
		//flag==1 删除事件监听者，并删除事件
		boolean result=false;
		Log.i(TAG, "注销监听者开始");
		if(listenermap.containsKey(eventName))
		{
			List<Listener> listeners=listenermap.get(eventName);
			Listener getlistener=getListenerInListenersByObserver(listeners,observer);	
			if(getlistener!=null)
			{
				if(!getlistener.isActionExist(eventName))
				{
					listeners.remove(getlistener);
					result=true;
					Log.i(TAG, "注销监听者成功");
				}
				else
				{
					if(flag==0)
					{
						Log.e(TAG, "监听者已监听广播"+eventName+"，请注销广播");
						result=false;
					}
					else
					{
						if(flag==1)
						{
							Log.d(TAG, "监听者已监听广播"+eventName);
							result=unRegisterBroadCastLisener(context,observer,eventName);
							
							listeners.remove(getlistener);
							Log.i(TAG, "注销监听者成功");
						}
					}
				}
			}
			else
			{
				Log.d(TAG, "事件"+eventName+"未存在的监听者");
				result=true;
			}

			Log.d(TAG, "事件 "+eventName+" 剩余监听者数: "+listenermap.get(eventName).size());
		}
		else
		{
			Log.w(TAG, "未存在的事件:"+eventName);
			result=false;
		}
		return result;
	}
	
	private static void reRigsterBroadCast(Context context,Listener getlistener,String eventName)
	{
		getlistener.unRregisterBroadCast(context);
		getlistener.deleteAction(eventName);
		if(getlistener.isActionExist(eventName))
		{
			getlistener.registerBroadCast(context); 
			Log.i(TAG, "重新注销广播成功"); 
		}
		else
		{
			Log.i(TAG, "监听广播数为0");
		}
		Log.i(TAG, "注销广播成功");
	}
	
	
	private static   boolean unRegisterAllLisenerByEventName(Context context,String eventName,int flag)
	{
		//flag==0  删除全部监听者
		//flag==1 删除广播监听者
		//flag==2 删除普通监听者
		
		boolean result=false;
		
		if(listenermap.containsKey(eventName))
		{
			List<Listener> listeners=listenermap.get(eventName);

			for(Iterator<Listener> iter=listeners.iterator();iter.hasNext();)
			{
				Listener tempListener=iter.next();
				
				if(flag==1||flag==0)
				{
					if(tempListener.isActionExist(eventName))
					{		
						reRigsterBroadCast(context,tempListener,eventName);
						Log.i(TAG, "删除广播监听者"+tempListener.getObserver());
					}
				}
				
				if(flag==2||flag==0)
				{
					if(!tempListener.isActionExist(eventName))
					{
						iter.remove();
						Log.i(TAG, "删除普通监听者"+tempListener.getObserver());
					}
				}
			}
			
			result=true;
			
		}
		else
		{
			Log.i(TAG, "未存在的事件"+eventName);
			result=false;
		}
		
		return result;
	}
	
	private static boolean unRegisterAllEvents(Context context,Observer observer,int flag)
	{
		//flag==0  删除全部事件
		//flag==1 删除广播事件
		//flag==2 删除普通事件
		
		boolean result=false;
	
		Iterator iter = listenermap.entrySet().iterator();
		while (iter.hasNext()) 
		{
			Map.Entry entry = (Map.Entry) iter.next();
			
			String eventName=(String) entry.getKey();
			
			List<Listener> listeners=(List<Listener>)entry.getValue();
			
			Listener getlistener=getListenerInListenersByObserver(listeners,observer);	
			if(getlistener!=null)
			{
				if(flag==1||flag==0)
				{
					if(getlistener.isActionExist(eventName))
					{
						reRigsterBroadCast(context,getlistener,eventName);
						result=true;
						Log.i(TAG, "注销广播事件"+eventName+"中的监听者"+getlistener.getObserver()+"成功");
					}
				}
				if(flag==2||flag==0)
				{
					if(!getlistener.isActionExist(eventName))
					{
						listeners.remove(getlistener);
						result=true;
						Log.i(TAG, "注销普通事件"+eventName+"中的监听者"+getlistener.getObserver()+"成功");
					}
				}
				
			}

			Log.d(TAG, "事件 "+eventName+" 剩余监听者数: "+listenermap.get(eventName).size());
		
		}
		
		return result;
	}
	
	
	public static boolean clear(Context context)
	{
		boolean result=false;
		
		Iterator iter = listenermap.entrySet().iterator();
		while (iter.hasNext()) 
		{
			Map.Entry entry = (Map.Entry) iter.next();
			
			String eventName=(String) entry.getKey();
			
			unRegisterAllLisenerByEventName(context, eventName);
			iter.remove();
		}
		
		return result;
	}
}



